package cn.yr.clock.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.yr.clock.domain.entity.User;
import cn.yr.clock.handler.CacheUserHandler;
import cn.yr.common.exception.ret.Ret;
import cn.yr.common.exception.ret.RetCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 登录拦截器
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private CacheUserHandler cacheUserHandler;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        User user = cacheUserHandler.getUser(request);
        log.debug("登录信息:{}", JSONUtil.toJsonStr(user));
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        if(ObjectUtil.isNull(user)){
            PrintWriter writer = response.getWriter();
            writer.write(JSONUtil.toJsonStr(Ret.error(RetCode.REQUEST_AUTHENTICATION__ERROR)));
            return false;
        }
        return true;
    }
}

